package com.yxkj.syh.app.huarong.activities.account.login.ver;

import android.annotation.SuppressLint;
import android.app.Application;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.alibaba.android.arouter.launcher.ARouter;
import com.syh.app.basic.base.BaseResponse;
import com.syh.app.basic.base.view_model.BaseViewModel;
import com.syh.app.basic.bindingAdp.view_click.ClickEvent;
import com.syh.app.basic.utils.Tooast;
import com.yxkj.syh.app.huarong.util.UserManager;
import com.syh.app.basic.utils.net.ApiObserver;
import com.syh.app.basic.utils.regex.RegexUtils;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.yxkj.syh.app.huarong.R;
import com.yxkj.syh.app.huarong.bean.LoginResponse;
import com.yxkj.syh.app.huarong.bean.UserInfoResponse;
import com.yxkj.syh.app.huarong.constants.ArouterPath;
import com.yxkj.syh.app.huarong.data_center.model.AccountModel;
import com.yxkj.syh.app.huarong.data_center.model.AuthModel;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * 创建者：SYH
 * 时间：2020/5/19 10:36
 * 编辑者：SYH、
 * 标签：
 * 补充说明：
 */
public class VerCodeLoginVM extends BaseViewModel<FragmentEvent> {
    private Disposable mDisposable;

    public VerCodeLoginVM(@NonNull Application application) {
        super(application);
    }

    public ObservableField<String> ofPhone = new ObservableField<String>("13645602857") {
        @Override
        public void set(String value) {
            super.set(value);
            if (!TextUtils.isEmpty(value) && !TextUtils.isEmpty(ofVerCode.get())) {
                if (!ofLoginEnable.get()) {
                    ofLoginEnable.set(true);
                }
            } else {
                if (ofLoginEnable.get()) {
                    ofLoginEnable.set(false);
                }
            }
        }
    };
    public ObservableField<String> ofVerCode = new ObservableField<String>() {
        @Override
        public void set(String value) {
            super.set(value);
            if (!TextUtils.isEmpty(value) && !TextUtils.isEmpty(ofPhone.get())) {
                if (!ofLoginEnable.get()) {
                    ofLoginEnable.set(true);
                }
            } else {
                if (ofLoginEnable.get()) {
                    ofLoginEnable.set(false);
                }
            }
        }
    };
    public ObservableField<String> ofGetVerCode = new ObservableField<>(getApplication().getString(R.string.get_ver_code));
    public ObservableField<Boolean> ofLoginEnable = new ObservableField<>(Boolean.FALSE);
    public ObservableField<Boolean> ofVerCodeEnable = new ObservableField<>(Boolean.TRUE);

    public ClickEvent verCodeClick = new ClickEvent() {
        @Override
        public void onClick(View view) {
            verCode();
        }
    };
    public ClickEvent loginClick = new ClickEvent() {
        @Override
        public void onClick(View view) {
            Map<String, Object> pMap = new HashMap<>();
            pMap.put("username", ofPhone.get());
            pMap.put("code", ofVerCode.get());
            AuthModel.getAuthModel().login(pMap, mLifecycleProvider.bindToLifecycle(), new ApiObserver<LoginResponse>() {
                @Override
                public void onSuccess(LoginResponse loginResponse) {
                    UserManager.getUserManager().saveToken(loginResponse.getData());
                    userInfo();
                }

                @Override
                public void onFailed(int code, String msg) {
                    Tooast.warning(msg);
                }
            });
        }
    };


    private void userInfo(){
//        AccountModel.getAccountModel().userInfo(mLifecycleProvider.bindToLifecycle(), new ApiObserver<UserInfoResponse>() {
//            @Override
//            public void onSuccess(UserInfoResponse userInfoResponse) {
//                UserManager.getUserManager().saveUser(userInfoResponse.getData());
//                ARouter.getInstance().build(ArouterPath.MAIN_ACTIVITY).navigation();
//                finish();
//            }
//
//            @Override
//            public void onFailed(int code, String msg) {
//                Tooast.warning(msg);
//            }
//        });
    }

    @SuppressLint("CheckResult")
    private void getVerCodeTimer() {
        Observable.interval(0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                        ofVerCodeEnable.set(false);
                    }

                    @Override
                    public void onNext(Long aLong) {
                        if (60 - aLong > 0) {
                            ofGetVerCode.set(60 - aLong + "s " + getApplication().getString(R.string.reget));
                        } else {
                            ofGetVerCode.set(getApplication().getString(R.string.get_ver_code));
                            ofVerCodeEnable.set(true);
                            mDisposable.dispose();
                            mDisposable = null;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mDisposable.dispose();
                        mDisposable = null;
                    }

                    @Override
                    public void onComplete() {
                        mDisposable.dispose();
                        mDisposable = null;
                    }
                });
    }

    /**
     * 获取验证码
     */
    private void verCode() {
        if (TextUtils.isEmpty(ofPhone.get())) {
            Tooast.normalInfo("请输入手机号");
        } else {
            if (!RegexUtils.isMobileSimple(ofPhone.get().trim())) {
                Tooast.normalInfo("手机格式不正确");
            } else {
                Map<String, Object> pMap = new HashMap<>();
                pMap.put("mobile", ofPhone.get());
                AuthModel.getAuthModel().verCode(pMap, mLifecycleProvider.bindToLifecycle(), new ApiObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        Tooast.success("请注意查收验证码");
                        getVerCodeTimer();
                    }

                    @Override
                    public void onFailed(int code, String msg) {
                        Tooast.warning(msg);
                    }
                });
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }
}
